import React, { useState, useEffect } from 'react';
import { View, Text, Image, TouchableOpacity, StyleSheet, Alert, PermissionsAndroid, Platform } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import Geolocation from 'react-native-geolocation-service';
import api from '../services/api';
import { logout } from '../store/userSlice';
import CustomHeader from '../components/CustomHeader';

const ProfileScreen = ({ navigation }) => {
  const userInfo = useSelector(state => state.user.userInfo);
  const dispatch = useDispatch();
  const [loading, setLoading] = useState(false);
  const [userStats, setUserStats] = useState({
    likedBy: '0',
    liked: '0',
    visitors: '0',
    newVisitors: '0'
  });

  // 计算用户资料完整度
  const calculateProfileCompletion = (user) => {
    if (!user) return 0;
    
    let completedFields = 0;
    const totalFields = 10; // 总共计算的字段数量
    
    // 必填字段
    if (user.name) completedFields += 1;
    if (user.avatar) completedFields += 1;
    if (user.gender) completedFields += 1;
    if (user.birthday) completedFields += 1;
    
    // 可选但重要的字段
    if (user.nickname) completedFields += 1;
    if (user.photos && user.photos.length > 0) completedFields += 1;
    if (user.introduction) completedFields += 1;
    if (user.location) completedFields += 1;
    if (user.occupation) completedFields += 1;
    if (user.education) completedFields += 1;
    
    return Math.round((completedFields / totalFields) * 100);
  };

  const profileCompletion = calculateProfileCompletion(userInfo);

  useEffect(() => {
    fetchUserStats();
  }, []);

  const fetchUserStats = async () => {
    try {
      const response = await api.getUserStats();
      if (response.success) {
        setUserStats(response.data);
      }
    } catch (error) {
      console.log('获取用户统计数据失败:', error);
    }
  };

  const handleLogout = () => {
    dispatch(logout());
    navigation.reset({
      index: 0,
      routes: [{ name: 'Login' }],
    });
  };

  // 请求位置权限
  const requestLocationPermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          {
            title: '位置权限请求',
            message: '此应用需要访问您的位置信息来确定您所在的国家',
            buttonNeutral: '稍后询问',
            buttonNegative: '取消',
            buttonPositive: '确定',
          },
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('位置权限已授予');
          return true;
        } else {
          console.log('位置权限被拒绝');
          return false;
        }
      } catch (err) {
        console.warn('请求位置权限时出错:', err);
        return false;
      }
    }
    // iOS默认会弹出权限请求
    return true;
  };

  // 获取当前位置并更新到服务器
  const getCurrentLocation = async () => {
    console.log('点击了获取位置按钮');
    
    // 检查是否安装了Geolocation模块
    if (!Geolocation) {
      Alert.alert('错误', '地理位置模块未正确安装');
      return;
    }
    
    // 请求位置权限
    const hasPermission = await requestLocationPermission();
    if (!hasPermission) {
      Alert.alert('权限被拒绝', '无法获取您的位置信息，请在设置中开启位置权限');
      return;
    }
    
    console.log('开始请求位置信息');
    
    // 获取位置信息
    Geolocation.getCurrentPosition(
      async (position) => {
        console.log('成功获取位置信息:', position);
        const { latitude, longitude } = position.coords;
        
        try {
          // 使用逆地理编码获取位置描述（这里简化处理）
          const locationString = `${latitude.toFixed(6)}, ${longitude.toFixed(6)}`;
          
          // 发送到服务器更新位置
          console.log('准备发送位置信息到服务器');
          const response = await api.updateUserLocation({
            latitude,
            longitude,
            location: locationString
          });
          console.log('服务器响应:', response);
          
          if (response.success) {
            Alert.alert('成功', '位置信息已更新');
            // 更新用户统计数据
            fetchUserStats();
          } else {
            Alert.alert('错误', response.message || '更新位置信息失败');
          }
        } catch (error) {
          console.log('更新位置信息失败:', error);
          Alert.alert('错误', '更新位置信息失败: ' + error.message);
        }
      },
      (error) => {
        console.log('位置获取失败:', error);
        let errorMessage = '无法获取您的当前位置，请确保已开启定位权限和GPS。';
        switch(error.code) {
          case 1:
            errorMessage = '位置权限被拒绝，请在设置中开启位置权限';
            break;
          case 2:
            errorMessage = '位置信息不可用，请检查GPS是否开启';
            break;
          case 3:
            errorMessage = '获取位置信息超时，请稍后重试';
            break;
          default:
            errorMessage = `获取位置失败: ${error.message}`;
        }
        Alert.alert('位置获取失败', errorMessage);
      },
      {
        enableHighAccuracy: true,
        timeout: 15000,
        maximumAge: 10000,
        forceRequestLocation: true, // 强制请求位置
        showLocationDialog: true,   // 显示位置对话框（Android）
      }
    );
  };

  return (
    <View style={styles.container}>
      <CustomHeader title="我的" showMenuButton={true} />
      
      {/* 头像和用户名区域 */}
      <TouchableOpacity 
        style={styles.header}
        onPress={() => navigation.navigate('EditProfile')}
      >
        <View style={styles.avatarContainer}>
          <Image 
            source={{ uri: (userInfo?.photos && userInfo.photos[0]) || userInfo?.avatar || 'https://via.placeholder.com/150' }} 
            style={styles.avatar} 
          />
          <View style={styles.completionBadge}>
            <Text style={styles.completionText}>{profileCompletion}%</Text>
          </View>
        </View>
        <View style={styles.userInfo}>
          <View style={styles.usernameContainer}>
            <Text style={styles.username}>{userInfo?.name || '未设置'}</Text>
            <View style={styles.badges}>
              <View style={styles.badgeVerified}>
                <Text style={styles.badgeText}>✓</Text>
              </View>
              {userInfo?.isVip && (
                <View style={styles.badgeSVIP}>
                  <Text style={styles.badgeText}>SVIP</Text>
                </View>
              )}
            </View>
          </View>
          <Text style={styles.accountInfo}>
            ID: {userInfo?.id || '未知'} | {userInfo?.gender === 'male' ? '男性' : userInfo?.gender === 'female' ? '女性' : '未设置'}
          </Text>
        </View>
      </TouchableOpacity>
      
      {/* 状态区域 */}
      <View style={styles.statusContainer}>
        <TouchableOpacity style={styles.statusButton}>
          <Text style={styles.statusText}>编辑个性签名</Text>
        </TouchableOpacity>
        <View style={styles.emojis}>
          {['😊', '😄', '😍', '😎'].map((emoji, index) => (
            <TouchableOpacity key={index} style={styles.emojiButton}>
              <View style={styles.emojiPlaceholder}>
                <Text style={styles.emojiText}>{emoji}</Text>
              </View>
            </TouchableOpacity>
          ))}
        </View>
      </View>
      
      {/* 统计信息 */}
      <View style={styles.statsContainer}>
        <TouchableOpacity 
          style={styles.statItem}
          onPress={() => navigation.navigate('Likes')}
        >
          <Text style={styles.statValue}>{userStats.likedBy}</Text>
          <Text style={styles.statLabel}>喜欢</Text>
          <View style={styles.badge}>
            <Text style={styles.badgeText}>1</Text>
          </View>
        </TouchableOpacity>
        
        <TouchableOpacity 
          style={styles.statItem}
          onPress={() => navigation.navigate('Visitors')}
        >
          <Text style={styles.statValue}>{userStats.visitors}</Text>
          <Text style={styles.statLabel}>看过我</Text>
          <View style={styles.badge}>
            <Text style={styles.badgeText}>{userStats.newVisitors}</Text>
          </View>
        </TouchableOpacity>
      </View>

      {/* VIP和充值功能 */}
      <View style={styles.vipRechargeContainer}>
        <View style={styles.diamondsInfo}>
          <Text style={styles.diamondsText}>粉钻余额: {userInfo?.diamonds || 0}</Text>
        </View>
        
        <View style={styles.vipRechargeButtons}>
          <TouchableOpacity 
            style={styles.vipButton}
            onPress={() => navigation.navigate('Vip')}
          >
            <Text style={styles.vipButtonText}>开通VIP</Text>
          </TouchableOpacity>
          
          <TouchableOpacity 
            style={styles.rechargeButton}
            onPress={() => navigation.navigate('Recharge')}
          >
            <Text style={styles.rechargeButtonText}>充值粉钻</Text>
          </TouchableOpacity>
        </View>
      </View>

      {/* 获取当前位置按钮 */}
      <TouchableOpacity 
        style={styles.locationButton} 
        onPress={getCurrentLocation}
      >
        <Text style={styles.locationButtonText}>获取当前位置</Text>
      </TouchableOpacity>

      {/* 退出登录按钮 */}
      <TouchableOpacity 
        style={styles.logoutButton} 
        onPress={handleLogout}
      >
        <Text style={styles.logoutButtonText}>退出登录</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 20,
    backgroundColor: 'white',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  avatarContainer: {
    position: 'relative',
  },
  avatar: {
    width: 80,
    height: 80,
    borderRadius: 40,
    borderWidth: 4,
    borderColor: '#ff8c00',
  },
  completionBadge: {
    position: 'absolute',
    bottom: 0,
    right: 0,
    backgroundColor: '#ff8c00',
    borderRadius: 10,
    paddingHorizontal: 6,
    paddingVertical: 2,
  },
  completionText: {
    color: 'white',
    fontSize: 10,
    fontWeight: 'bold',
  },
  userInfo: {
    marginLeft: 16,
  },
  usernameContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  username: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#000',
  },
  badges: {
    flexDirection: 'row',
    marginLeft: 8,
  },
  badgeVerified: {
    backgroundColor: '#00bfff',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
    marginRight: 8,
  },
  badgeSVIP: {
    backgroundColor: '#ff8c00',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  badgeText: {
    color: 'white',
    fontSize: 12,
    fontWeight: 'bold',
  },
  accountInfo: {
    fontSize: 14,
    color: '#666',
    marginTop: 4,
  },
  statusContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 20,
    backgroundColor: 'white',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  statusButton: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderWidth: 1,
    borderColor: '#e0e0e0',
    borderRadius: 8,
  },
  statusText: {
    color: '#000',
    fontSize: 14,
  },
  emojis: {
    flexDirection: 'row',
    marginLeft: 16,
  },
  emojiButton: {
    marginHorizontal: 8,
  },
  emojiPlaceholder: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: '#f0f0f0',
    justifyContent: 'center',
    alignItems: 'center',
  },
  emojiText: {
    fontSize: 18,
  },
  statsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingVertical: 20,
    backgroundColor: 'white',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  statItem: {
    alignItems: 'center',
    position: 'relative',
  },
  statValue: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#000',
  },
  statLabel: {
    fontSize: 12,
    color: '#666',
    marginTop: 4,
  },
  badge: {
    position: 'absolute',
    top: -8,
    right: -8,
    backgroundColor: '#ff4444',
    paddingHorizontal: 6,
    paddingVertical: 2,
    borderRadius: 12,
  },
  vipRechargeContainer: {
    backgroundColor: 'white',
    margin: 16,
    borderRadius: 8,
    padding: 16,
  },
  diamondsInfo: {
    marginBottom: 16,
  },
  diamondsText: {
    fontSize: 16,
    color: '#333',
  },
  vipRechargeButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  vipButton: {
    backgroundColor: '#ff8c00',
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 8,
  },
  vipButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
  rechargeButton: {
    backgroundColor: '#2196F3',
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 8,
  },
  rechargeButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
  locationButton: {
    backgroundColor: '#4CAF50',
    marginHorizontal: 16,
    marginVertical: 8,
    padding: 16,
    borderRadius: 8,
    alignItems: 'center',
  },
  locationButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
  logoutButton: {
    backgroundColor: '#f44336',
    margin: 16,
    padding: 16,
    borderRadius: 8,
    alignItems: 'center',
  },
  logoutButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default ProfileScreen;